package com.zh.mediacommon.util;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.synonym.Synonym;
import com.hankcs.hanlp.dictionary.CoreSynonymDictionary;
import com.hankcs.hanlp.seg.common.Term;
import com.zh.mediacommon.ecxeption.NotFoundException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;



@Slf4j
public class HanLPUtil {
    private static List<String> segment(String text) {
        List<Term> termList = HanLP.segment(text);
        List<String> wordList = new ArrayList<>();
        for (Term term : termList){
            wordList.add(term.word);
        }
        return wordList;
    }
    private static Set<String> getSynonyms(String word){
        Set<String> synonyms = new HashSet<>();
        synonyms.add(word);
         if(CoreSynonymDictionary.get(word)!=null) {
             List<Synonym> synonymList = CoreSynonymDictionary.get(word).synonymList;
             for (Synonym synonym : synonymList) {
                 synonyms.add(synonym.realWord);
             }
         }
        return synonyms;
    }

    public static Set<String> recommendDepartments(String text,Map<String, List<String>> departmentKeywords) {
        List<String> words = segment(text); // 对用户输入进行分词
        Set<String> wordSet = new HashSet<>(words);
        Set<String> recommendedDepartments = new HashSet<>();

        // 遍历部门映射
        for (Map.Entry<String, List<String>> entry : departmentKeywords.entrySet()) {
            String department = entry.getKey();
            List<String> keywords = entry.getValue();

            for (String keyword : keywords) {
                // 获取关键词的同义词
                Set<String> synonyms = getSynonyms(keyword);

                // 检查是否有同义词在 wordSet 中
                for (String synonym : synonyms) {
                    if (wordSet.contains(synonym)) {
                        recommendedDepartments.add(department);
                        break; // 如果找到一个匹配的同义词，就可以跳出循环
                    }
                }
            }
        }

//        Set<String> recommendedDepartments = new HashSet<>();
//        for (Map.Entry<String, List<String>> entry : DepartmentMapUtil.getDepartmentMap().entrySet()) {
//            String department = entry.getKey();
//            List<String> keywords = entry.getValue();
//
//            for (String keyword : keywords) {
////                // 获取关键词的同义词
//                Set<String> synonyms = getSynonyms(keyword);
//                for (String word : words) {
//                    if (synonyms.contains(word)) {
//                        recommendedDepartments.add(department);
//                    }
//                }
//            }
//        }
        return recommendedDepartments;
    }
}
